export let pullRefresh = {
  data: function () {
    return {
      isPullRefreshStart: false,
      isPullRefreshLoading: false,
    }
  },
  mounted: function () {
    this.resetPullRefresh();
  },
  methods: {
    // 重定向下拉刷新，在下拉刷新的过程中，页面再往下滑动时，取消下拉刷新
    resetPullRefresh() {
      window.addEventListener('scroll', () => {
        let refreshTrackEl = document.querySelector('.van-pull-refresh__track');
        if (!refreshTrackEl) return;
        let scrollTop = document.body.scrollTop || document.documentElement.scrollTop;
        let translate3dY = parseInt(refreshTrackEl.style.transform.split(',')[1]);
        if (translate3dY > 0 && scrollTop > translate3dY) {
          this.pullRefreshLoading = false;
        }
      }, true);
    },
    // 刷新成功的回调
    pullRefreshSuccess() {
      if (this.isPullRefreshStart) {
        this.$toast({message: '已获取最新数据', duration: 800});
        this.isPullRefreshLoading = false;
        this.isPullRefreshStart = false;
      }
    },
    // 刷新失败回调
    pullRefreshFail() {
      this.isPullRefreshLoading = false;
      this.isPullRefreshStart = true;
    },
    // 下拉刷新
    onRefresh() {
      this.isPullRefreshStart = true;
      // 有分页的话，就进行重置，只请求第一页的数据
      if (this.pagination) {
        this.pagination.pageNum = 1;
      }
      this.fetchPage && this.fetchPage();
    },
  }
};

export let loadMore = {
  data: function () {
    return {
      isMoreLoading: true,
      isMoreFinished: false,
      isMoreError: false,
      isMoreVisible: false, // 是否可以首次进行加载显示
      pagination: {
        pageSize: 10,
        pageNum: 1,
      }
    }
  },
  methods: {
    // 加载更多成功
    loadMoreSuccess(params = {total: 0, length: 0}) {
      this.isMoreFinished = params.total === params.length;
      this.isMoreLoading = false;
      this.isMoreVisible = true;
    },
    // 分页后的成功数据进行合并
    getLoadMoreListConcat(newList, oldList) {
      // 第一页数据的话，就需要处理一下，只显示新数据
      return this.pagination.pageNum === 1 ? newList : (oldList || []).concat(newList)
    },
    // 加载失败
    loadMoreFail() {
      if (this.isMoreVisible) {
        this.isMoreLoading = false;
        this.isMoreLoading = true;
      }
    },
    // 开始加载更多
    onLoadMore() {
      this.pagination.pageNum += 1;
      this.onLoadFetch && this.onLoadFetch();
    },
  }
};
